package com.hy.springboot.common.utils;

import com.hy.springboot.common.config.NameThreadFactory;
import org.slf4j.MDC;

import java.util.Map;
import java.util.concurrent.*;

/**
 * 有返回值的异步任务
 * @author lccsetsun
 * @since 2024/2/3 10:01
 **/

public class FutureTaskUtils<T> {
	public static ThreadPoolExecutor executor =new ThreadPoolExecutor(
			5,
			10,
			1L,
			TimeUnit.SECONDS,
			new LinkedBlockingQueue<>(),new NameThreadFactory("hySync-task-pool-")
	);


//	public static void main(String[] args) {
////		Future<String> fs = executor.submit(wrap(new CallableTask("asd")));
//
//	}


	private static  <T> Callable<T> wrap(final Callable<T> callable) {
		// 获取当前线程的MDC上下文信息
		Map<String, String> context = MDC.getCopyOfContextMap();
		return () -> {
			if (context != null) {
				// 传递给子线程
				MDC.setContextMap(context);
			}
			try {
				return callable.call();
			} finally {
				// 清除MDC上下文信息，避免造成内存泄漏
				MDC.clear();
			}
		};
	}

	public static  Runnable wrap(final Runnable runnable) {
		Map<String, String> context = MDC.getCopyOfContextMap();
		return () -> {
			if (context != null) {
				MDC.setContextMap(context);
			}
			try {
				runnable.run();
			} finally {
				// 清除MDC上下文信息，避免造成内存泄漏
				MDC.clear();
			}
		};
	}

	public static Future submit(Runnable task) {
		return executor.submit(wrap(task));
	}
	public static Future submit(Callable task) {
		return executor.submit(wrap(task));
	}
}
